#include <unistd.h>
#include <netdb.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>

#define MAXLINE 1024

//const char operation_str[] = "{ \"cmd\": \"setLeds\", \"leds\": [\"Off\", \"off\", \"On\", \"on\"]}";
//const char operation_str[] = "{\"cmd\" : \"getTempHum\"}";
const char operation_str[] = "{\"cmd\":\"setFan\", \"fan\" : \"Off\"}";

int main(int argc, char* argv[])
{
    int	sockfd, n;
    char recvline[MAXLINE+1];
    struct sockaddr_in	servaddr;

//    if (argc != 2){
//        printf("usage: a.out <IPaddress>\n");
//        return 0;
//    }

    if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
        perror("[error] socket error.\n");
        exit (-1);
    }
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(8888);
    if (inet_pton(AF_INET, "192.168.10.11", &servaddr.sin_addr.s_addr) < 0){
        fprintf(stderr, "[error] inet_pton error for %s", argv[1]);
        return 0;
    }

    if (connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0){
        perror("[error] connect error");
        exit (-1);
    }

    n = write(sockfd, operation_str, strlen(operation_str));
    if (n != strlen(operation_str)){
        perror("[error] write to server error");
        exit (-1);
    }else{
        fprintf(stdout, "[log] write to server finished.\n");
    }

//    while ( (n = read(sockfd, recvline, MAXLINE)) > 0){
//        recvline[n] = 0;
//        if (fputs(recvline, stdout) == EOF){
//            perror("fputs error");
//            exit (-1);
//        }
//    }
//    if (n < 0){
//        perror("read error");
//    }

    close(sockfd);
    exit (0);
}
